package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 * 数据操作父类
 * @author acer
 *
 */
public class BaseDao {

	static Connection conn;
	protected PreparedStatement prep;
	protected ResultSet rs;

	private static String driver;
	private static String url;
	private static String username;
	private static String password;

	static {

		try {
			Properties properties = new Properties();
			properties.load(BaseDao.class.getClassLoader().getResourceAsStream("database.properties"));

			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			username = properties.getProperty("username");
			password = properties.getProperty("password");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static Connection getConnection() {
		try {
			//保证事务操作在一个连接中 不能打开新的连接
//			if(conn ==null){
				Class.forName(driver);
				conn = DriverManager.getConnection(url, username, password);
				//从连接池获取连接
				//1.Context
//				Context context = new InitialContext();
//				//2.lookup
//				DataSource dataSource = (DataSource)context.lookup("java:comp/env/jdbc/news");
//				conn = dataSource.getConnection();
			//}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	/**
	 * 通用执行count(1)
	 * @param sql
	 * @param objs
	 * @return
	 */
	public int executeCount(String sql, Object... objs){
		try {
			rs = executeQuery(sql, objs);
			if (rs.next()) {
				return rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	/**
	 * 通用查询
	 * 
	 * @param sql
	 * @param objs
	 * @return
	 * @throws DaoException
	 */
	public ResultSet executeQuery(String sql, Object... objs) {
		try {
			conn = getConnection();
			prep = conn.prepareStatement(sql);

			for (int i = 0; i < objs.length; i++) {
				if(objs[i]!=null)
					prep.setObject(i + 1, objs[i]);
			}
			System.err.println(prep);
			return prep.executeQuery();
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 通用增删改
	 * 
	 * @param sql
	 * @param objs
	 * @return
	 * @throws DaoException
	 */
	public int executeUpdate(String sql, Object... objs) {
		try {
			conn = getConnection();
			prep = conn.prepareStatement(sql);

			for (int i = 0; i < objs.length; i++) {
				prep.setObject(i + 1, objs[i]);
			}
			System.err.println(prep);
			return prep.executeUpdate();
		} catch (Exception e) {
		}
		return 0;
	}

	public static void close() {

		try {
//			if (rs != null)
//				rs.close();
//			if (prep != null)
//				prep.close();

			if (conn != null){
				conn.close();
				conn = null;
			}

		} catch (Exception e) {
		}
	}
}
